const { defaultDatabaseService } = require('../database-service');

async function testAuditFunctionality() {
  try {
    console.log('🔍 正在测试审计功能...');
    
    // 连接数据库
    await defaultDatabaseService.connect();
    console.log('✅ 数据库连接成功');
    
    // 插入测试任务
    const taskId = 'audit-test-' + Date.now();
    const insertSQL = `
      INSERT INTO TaskList (
        id, Task_No, Job_Style, Unload_Line, Unload_Col, Unload_Layer, is_issued, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const params = [
      taskId,
      'AUDIT-001',
      '审计测试任务',
      1,
      1,
      1,
      0,
      new Date().toISOString(),
      new Date().toISOString()
    ];
    
    await defaultDatabaseService.insert(insertSQL, params);
    console.log('✅ 测试任务插入成功');
    
    // 更新任务状态
    const updateSQL = "UPDATE TaskList SET is_issued = ?, updated_at = ? WHERE id = ?";
    await defaultDatabaseService.update(updateSQL, [1, new Date().toISOString(), taskId]);
    console.log('✅ 任务状态更新成功');
    
    // 查询审计记录
    const auditSQL = "SELECT * FROM tasklist_audit WHERE task_id = ? ORDER BY changed_at";
    const auditRecords = await defaultDatabaseService.query(auditSQL, [taskId]);
    
    if (auditRecords.length > 0) {
      console.log(`✅ 找到 ${auditRecords.length} 条审计记录:`);
      auditRecords.forEach(record => {
        console.log(`  - ${record.change_type}: ${record.old_is_issued} -> ${record.new_is_issued} at ${record.changed_at}`);
      });
    } else {
      console.log('❌ 未找到审计记录');
    }
    
    // 清理测试数据
    const deleteSQL = "DELETE FROM TaskList WHERE id = ?";
    await defaultDatabaseService.delete(deleteSQL, [taskId]);
    
    const deleteAuditSQL = "DELETE FROM tasklist_audit WHERE task_id = ?";
    await defaultDatabaseService.delete(deleteAuditSQL, [taskId]);
    
    console.log('✅ 测试数据已清理');
    
    await defaultDatabaseService.disconnect();
    console.log('\n✅ 审计功能测试完成');
  } catch (error) {
    console.error('❌ 审计功能测试失败:', error.message);
    try {
      await defaultDatabaseService.disconnect();
    } catch (disconnectError) {
      console.error('❌ 数据库断开连接失败:', disconnectError.message);
    }
  }
}

// 执行测试
testAuditFunctionality();